<script setup>
import {
  SearchOutlined,
  DeleteOutlined,
  ExportOutlined,
  ExclamationCircleFilled,
  PictureOutlined,
  SmileOutlined,
  EditOutlined,
  SnippetsOutlined,
  InteractionOutlined,
  ClockCircleOutlined,
  AuditOutlined,
  ContactsOutlined
} from '@ant-design/icons-vue'
import EidtVolunteer from '../EditVolunteer/index.vue'
import PosterDetail from '../PosterDetail/index.vue'
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { h } from 'vue'
import {
  adminQueryVolunteerService,
  exportVolunteerService,
  adminUpdateVolunteerService
} from '@/api/volunteer.js'
import dayjs from 'dayjs'

const columns = [
  {
    title: '活动名称',
    dataIndex: 'activityName',
    key: 'activityName',
    align: 'center'
  },
  {
    title: '发布组织',
    dataIndex: 'organization',
    key: 'organization',
    align: 'center'
  },
  {
    title: '剩余名额',
    dataIndex: 'remainder',
    key: 'remainder',
    align: 'center'
  },
  {
    title: '持续时间',
    dataIndex: 'duration',
    key: 'duration',
    align: 'center'
  },
  {
    title: '活动详情',
    key: 'activedetail',
    dataIndex: 'activedetail',
    align: 'center'
  },
  {
    title: '标签',
    key: 'tag',
    dataIndex: 'tag',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    align: 'center'
  }
]
const editId = ref(0)
const editRef = ref()
const onEidt = (item) => {
  console.log(item)
  editRef.value.showModal()
  editId.value = item.id
  console.log(editId.value)
}
// 自定义图标为红色
const customIcon = h(ExclamationCircleFilled, { style: { color: 'red' } })

const deleteActivity = async (id) => {
  // 执行删除逻辑
  const res = await adminUpdateVolunteerService({
    id,
    deleted: 1
  })
  if (res.data.code === 1) {
    message.success('志愿活动删除完成')
    getVolunteerList()
  }
}

const cancelDelete = () => {
  message.info('取消删除操作')
}
//展示海报相关代码
const posterRef = ref()
const posterId = ref(0)
const posterTitle = ref()
const onDisplayPoster = (record) => {
  posterId.value = record.id
  posterTitle.value = record.activityName
  posterRef.value.showModal()
}

const parameterModel = ref({
  pageNo: 1,
  pageSize: 10,
  activityName: ''
})

const total = ref(0) // 总记录数
const formModel = ref([])
const loading = ref(false)
//获取志愿者活动列表
const getVolunteerList = async () => {
  loading.value = true
  const res = await adminQueryVolunteerService(parameterModel.value)
  console.log(res)
  formModel.value = res.data.data.records
  total.value = res.data.data.pages // 更新总记录数

  // 遍历并更新每个对象的 `activedetail` 属性
  formModel.value.forEach((item) => {
    const activedetail = []
    // 判断人数状态
    if (item.remainder > 0) {
      activedetail.push('人数未满')
    } else {
      activedetail.push('人数已满')
    }
    // 获取当前时间
    const now = dayjs()
    // 判断活动时间状态
    const beginTime = dayjs(item.beginTime)
    const endTime = dayjs(item.endTime)

    if (now.isBefore(beginTime)) {
      activedetail.push('未开始')
    } else if (now.isAfter(endTime)) {
      activedetail.push('已结束')
    } else {
      activedetail.push('报名中')
    }
    // 生成持续时间的字符串格式
    item.duration = `${item.beginTime} ~ ${item.endTime}`
    // 添加 `activedetail` 属性到对象
    item.activedetail = activedetail
    if (item.tag) {
      item.tag = item.tag.replace(/\[|,|，|\]/g, '')
      item.tag = (item.tag || '').split(/\s+/)
    }
  })
  loading.value = false
}
getVolunteerList()

// 分页变化时的处理
const handlePageChange = (page) => {
  parameterModel.value.pageNo = page
  getVolunteerList()
}
const onExport = async (record) => {
  const res = await exportVolunteerService(record.id)
  // 判断是否请求成功
  if (res && res.status === 200) {
    // 创建一个 Blob 对象
    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // 创建下载链接
    const link = document.createElement('a')
    const fileName = record.activityName + '名单.xlsx' // 可以根据需求修改文件名

    // 创建 Object URL 并触发下载
    link.href = URL.createObjectURL(blob)
    link.download = fileName
    link.click()

    // 可选：释放 Object URL
    URL.revokeObjectURL(link.href)
  }
}
const onSearch = () => {
  getVolunteerList()
}
</script>
<template>
  <a-input-search
    v-model:value="parameterModel.activityName"
    placeholder="请输入志愿活动名称"
    style="width: 400px; margin-right: 18px"
    enter-button
    @search="onSearch"
  />
  <br />
  <br />
  <a-table
    :columns="columns"
    :data-source="formModel"
    :loading="loading"
    :pagination="false"
  >
    <template #headerCell="{ column }">
      <template v-if="column.key === 'activityName'">
        <span>
          <SmileOutlined />
          活动名称
        </span>
      </template>
      <template v-if="column.key === 'organization'">
        <span>
          <AuditOutlined />
          发布组织
        </span>
      </template>
      <template v-if="column.key === 'remainder'">
        <span>
          <ContactsOutlined />
          剩余名额
        </span>
      </template>
      <template v-if="column.key === 'duration'">
        <span>
          <ClockCircleOutlined />
          持续时间
        </span>
      </template>
      <template v-if="column.key === 'activedetail'">
        <span>
          <EditOutlined />
          活动详情
        </span>
      </template>
      <template v-if="column.key === 'tag'">
        <span>
          <SnippetsOutlined />
          标签
        </span>
      </template>
      <template v-if="column.key === 'action'">
        <InteractionOutlined />
        操作
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'name'">
        <a>
          {{ record.name }}
        </a>
      </template>
      <template v-else-if="column.key === 'remainder'">
        <a> {{ record.remainder }} / {{ record.recruitNumber }} </a>
      </template>
      <template v-else-if="column.key === 'activedetail'">
        <span>
          <a-tag
            v-for="tag in record.activedetail"
            :key="tag"
            :color="
              tag === '未开始'
                ? 'blue'
                : tag === '报名中'
                  ? 'green'
                  : tag === '已结束'
                    ? 'red'
                    : tag === '人数已满'
                      ? 'red'
                      : tag === '人数未满'
                        ? 'green'
                        : 'pink'
            "
          >
            {{ tag.toUpperCase() }}
          </a-tag>
        </span>
      </template>
      <template v-else-if="column.key === 'tag'">
        <span>
          <a-tag
            v-for="tag in record.tag"
            :key="tag"
            :color="tag.length < 3 ? 'green' : 'red'"
          >
            {{ tag.toUpperCase() }}
          </a-tag>
        </span>
      </template>
      <template v-else-if="column.key === 'action'">
        <span>
          <a-button type="primary" @click="onEidt(record)">
            <template #icon>
              <SearchOutlined />
            </template>
            查看详情
          </a-button>
          <a-divider type="vertical" />
          <a-button
            type="primary"
            style="background-color: #ffd700"
            danger
            @click="onDisplayPoster(record)"
          >
            <template #icon>
              <PictureOutlined />
            </template>
            活动海报
          </a-button>
          <a-divider type="vertical" />
          <a-button
            type="primary"
            style="background-color: #00b96b"
            danger
            @click="onExport(record)"
          >
            <template #icon>
              <ExportOutlined />
            </template>
            导出名单
          </a-button>
          <a-divider type="vertical" />

          <a-popconfirm
            :icon="customIcon"
            title="确定要删除这个志愿活动吗？"
            okText="确认"
            cancelText="取消"
            @confirm="deleteActivity(record.id)"
            @cancel="cancelDelete"
          >
            <a-button type="primary" danger>
              <template #icon>
                <DeleteOutlined />
              </template>
              撤销活动
            </a-button>
          </a-popconfirm>
        </span>
      </template>
    </template>
  </a-table>
  <!-- 分页器 -->
  <br />
  <a-pagination
    :current="parameterModel.pageNo"
    :page-size="parameterModel.pageSize"
    :total="total"
    @change="handlePageChange"
    show-less-items
    style="float: right"
  />
  <poster-detail
    ref="posterRef"
    :posterId="posterId"
    :posterTitle="posterTitle"
  />
  <eidt-volunteer
    ref="editRef"
    :editId="editId"
    :getVolunteerList="getVolunteerList"
  />
</template>
